package com.LeeCode;

import java.util.HashMap;

/**
 * K 个不同整数的子数组
 */

public class Code992 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 1, 3, 4};
        int k = 3;
        System.out.println(new Code992().subarraysWithKDistinct(nums, k));
    }

    public int subarraysWithKDistinct(int[] nums, int k) {
        return aux(nums, k) - aux(nums, k + 1);
    }

    private int aux(int[] nums, int k) {
        int ans = 0, left = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int right = 0; right < nums.length; right++) {
            map.merge(nums[right], 1, Integer::sum);
            while (map.size() >= k) {
                map.merge(nums[left], -1, (old, delta) -> {
                    int res = old + delta;
                    return res > 0 ? res : null;
                });
                left++;
            }
            ans += left;
        }
        return ans;
    }
}
